package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.entity.SysDept;
import com.pactera.madp.admin.api.entity.SysUser;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.data.tenant.TenantContextHolder;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.cp.api.bo.ContactLossBO;
import com.pactera.madp.cp.api.constant.DeptConstants;
import com.pactera.madp.cp.api.dto.contact.ContactByTagDto;
import com.pactera.madp.cp.api.dto.contactLoss.ContactLossDetailsTendencyDTO;
import com.pactera.madp.cp.api.dto.contactLoss.ContactNoCommunicationTendencyDTO;
import com.pactera.madp.cp.api.dto.contactLoss.LossDto;
import com.pactera.madp.cp.api.dto.msg.MsgVo;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.clientLossManagement.ContactLossEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindCommunicationEntity;
import com.pactera.madp.cp.api.entity.wm.WorkMsgEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.contactloss.*;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.wm.WorkMsgHelper;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.ContactMapper;
import com.pactera.madp.cp.mapper.clientLossManagement.ContactLossMapper;
import com.pactera.madp.cp.mapper.wm.WorkMsgMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.pactera.madp.cp.service.impl.WorkContactEmployeeStaticsServiceImpl.getDetHashList;

/**
 * @date: 2021/7/28 11:21
 * @description:
 */
@Service
@Slf4j
public class ContactLossServiceImpl extends ServiceImpl<ContactLossMapper, ContactLossEntity> implements IContactLossService {

    @Autowired
    private IWorkDeptService workDeptService;
    @Autowired
    private IWorkEmployeeDepartmentService workEmployeeDepartmentService;
    @Autowired
    private IWorkContactService workContactService;
    @Autowired
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private IWorkMsgService workMsgService;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private RemindCommunicationService remindCommunicationService;
    @Autowired
    private ContactLossMapper contactLossMapper;
    @Autowired
    private ContactMapper contactMapper;
    @Autowired
    private WorkMsgMapper workMsgMapper;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private IWorkEmployeeService employeeService;

    @Override
    public Page queryByDto(Page page, Integer employeeId) {
        Integer corpId = CorpContextHolder.getCorpId();
        Integer userId = SecurityUtils.getUser().getId();
        Integer id = workEmployeeService.getObj(Wrappers.<WorkEmployeeEntity>query().eq("log_user_id", userId).eq("corp_id", corpId), o -> Integer.parseInt(o.toString()));
        List<Integer> deptIds = workEmployeeDepartmentService.listObjs(Wrappers.<WorkEmployeeDepartmentEntity>query()
                .select("department_id").eq("employee_id", id), o -> {
            return Integer.parseInt(o.toString());
        });
        ArrayList<Integer> allDeptIds = new ArrayList<>();
        deptIds.forEach(f -> {
            List<Integer> allChilds = workDeptService.getAllChilds(f);
            allDeptIds.addAll(allChilds);
        });
        //得到所有需要查询的部门
        List<Integer> employeeIds = workEmployeeDepartmentService.getEmployeeIdsByDepts(allDeptIds.stream().distinct().collect(Collectors.toList()));

        QueryWrapper<ContactLossEntity> wrapper = new QueryWrapper<ContactLossEntity>();
        if (employeeId != null) {
            wrapper.eq("employee_id", employeeId);
        } else {
            wrapper.eq("corp_id", corpId);
            wrapper.in("employee_id", employeeIds);
        }
        wrapper.orderByDesc("loss_time");
        IPage iPage = this.page(page, wrapper);
        List<ContactLossEntity> list = iPage.getRecords();
        List<Integer> contactIds = list.stream().map(m -> m.getContactId()).collect(Collectors.toList());
        if (contactIds.size() == 0) contactIds.add(null);
        //获得头像
        List<WorkContactEntity> contactEntities = workContactService.query().select("id", "avatar").in("id", contactIds).list();

        ArrayList<ContactLossVo> vos = new ArrayList<>();
        list.forEach(f -> {
            ContactLossVo vo = new ContactLossVo();
            BeanUtils.copyProperties(f, vo);
            contactEntities.forEach(c -> {
                if (c.getId().equals(f.getContactId())) vo.setContactAvatar(c.getAvatar());
            });
            long l = Duration.between(f.getBuildTime(), f.getLossTime()).toDays();
            vo.setAddTime(l);
            vos.add(vo);
        });
        // vos.sort(comparing(ContactLossVo::getLossTime).reversed());
        page.setRecords(vos);
        return page;
    }

    @Override
    public List<MsgVo> lossDetail(Page page, LossDto dto) {
        WorkEmployeeEntity employeeEntity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getId, dto.getContactId()));
        WorkContactEntity contactEntity = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getId, dto.getContactId()));
        QueryWrapper<WorkMsgEntity> wrapper = new QueryWrapper<>();
        JSONArray contact = new JSONArray();
        contact.add(contactEntity.getWxExternalUserid());
        JSONArray employee = new JSONArray();
        employee.add(employeeEntity.getWxUserId());
        wrapper.lambda().eq(WorkMsgEntity::getFrom, employeeEntity.getWxUserId()).eq(WorkMsgEntity::getTolist, employee);
        wrapper.lambda().or().eq(WorkMsgEntity::getFrom, contactEntity.getWxExternalUserid()).eq(WorkMsgEntity::getTolist, employee);
        wrapper.lambda().orderByDesc(WorkMsgEntity::getMsgTime);
        List<WorkMsgEntity> list = workMsgService.page(page, wrapper).getRecords();
        ArrayList<MsgVo> vos = new ArrayList<>();
        list.forEach(f -> {
            MsgVo vo = new MsgVo();
            BeanUtils.copyProperties(f, vo);
            translation(contactEntity, employeeEntity, vo, f);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public Integer getStatistic(LocalDate localDate, Integer corpId) {

        return baseMapper.getStatistic(localDate.toString(), corpId);
    }

    @Override
    public ObjListVO getObjListByDeptId(Integer deptId) {
        R r1 = remoteDeptService.getWxDeptId(deptId);
        WorkDeptEntity deptEntity = workDeptService.getOne(new LambdaQueryWrapper<WorkDeptEntity>()
                .eq(WorkDeptEntity::getWxDepartmentId, r1.getData()));
        Integer deptLevel = deptEntity.getLevel();

        if (deptLevel < DeptConstants.SUB_BRANCH_LEVEL) {
            //获取机构list
            Object data = remoteDeptService.getLowerDepts(deptId).getData();
            List<SysDept> deptList = JSON.parseArray(JSON.toJSONString(data), SysDept.class);
            ArrayList<ObjVO> objVOS = new ArrayList<ObjVO>();
            deptList.forEach(d -> {
                ObjVO objVO = new ObjVO();
                objVO.setObjectId(d.getDeptId());
                objVO.setObjectName(d.getName());
                objVOS.add(objVO);
            });
            ObjListVO objListVO = new ObjListVO();
            objListVO.setObjectList(objVOS);
            objListVO.setObjectListType("dept");
            return objListVO;
        } else {
            //获取成员list
            Object data = remoteDeptService.getUsers(deptId).getData();
            List<SysUser> userList = JSON.parseArray(JSON.toJSONString(data), SysUser.class);
            ArrayList<ObjVO> objVOS = new ArrayList<ObjVO>();
            userList.forEach(e -> {
                ObjVO objVO = new ObjVO();
                objVO.setObjectId(e.getUserId());
                objVO.setObjectName(e.getName());
                objVOS.add(objVO);
            });
            ObjListVO objListVO = new ObjListVO();
            objListVO.setObjectList(objVOS);
            objListVO.setObjectListType("employee");
            return objListVO;
        }
    }

    @Override
    public ContactLossPageVo getLossStatisticsDatas(Integer deptId, Integer wxDeptId) {
        ContactLossPageVo vo;
        Set<Integer> employeeIds = getEmployees(deptId);
        if (employeeIds == null || employeeIds.size() == 0) {
            vo = new ContactLossPageVo();
            vo.setContactTotalCount(0);
            vo.setContactLossTotalCount(0);
            vo.setWxLossCount(0);
            vo.setQywxLossCount(0);
            vo.setYesterdayNetGrowthCount(0);
            vo.setYesterdayLossCount(0);
            vo.setYesterdayAddedCount(0);
        } else {
            vo = getLossStatisticsData(employeeIds);
        }
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        vo.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        vo.setName(workDeptEntity.getName());
        return vo;
    }

    @Override
    public ContactLossPageVo getLossStatisticsData(Set<Integer> employeeIds) {
        Integer corpId = CorpContextHolder.getCorpId();

        //客户总数
        Integer contactTotalCount = workContactService.countByEmployeeIds(employeeIds, corpId, new DateTime().toDateStr() + " 23:59:59");

        //流失客户总数
        Integer contactLossTotalCount = 0;

        //流失微信客户数
        Integer wxLossCount = 0;

        //流失企业微信客户数
        Integer qywxLossCount = 0;

        //流失客户idList
//        List<Integer> lossContactIds = this.list(Wrappers.<ContactLossEntity>lambdaQuery()
//                .eq(ContactLossEntity::getCorpId, corpId)
//                .in(ContactLossEntity::getEmployeeId, employeeIds))
//                .stream()
//                .map(ContactLossEntity::getContactId)
//                .collect(Collectors.toList());
//        if (!lossContactIds.isEmpty()) {
//            Collection<WorkContactEntity> workContactEntities = workContactService.listByIds(lossContactIds);
//            contactLossTotalCount = workContactEntities.size();
//            wxLossCount = (int)workContactEntities.stream().filter(l->l.getType().equals(1)).count();
//            qywxLossCount = (int)workContactEntities.stream().filter(l->l.getType().equals(2)).count();
//        }
        List<ContactLossBO> lossContactList = contactLossMapper.getLossList(corpId, TenantContextHolder.getTenantId(), employeeIds, DateUtil.endOfDay(new DateTime()).toString());
        if (!lossContactList.isEmpty()) {
            contactLossTotalCount = lossContactList.size();
            wxLossCount = (int)lossContactList.stream().filter(l->l.getType().equals(1)).count();
            qywxLossCount = (int)lossContactList.stream().filter(l->l.getType().equals(2)).count();
        }

        //昨日新增数
        Integer yesterdayAddedCount = workContactEmployeeService.count(
                Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                        .eq(WorkContactEmployeeEntity::getCorpId, corpId)
                        .in(WorkContactEmployeeEntity::getEmployeeId, employeeIds)
                        .ge(WorkContactEmployeeEntity::getCreateTime,DateUtil.yesterday().toDateStr() + " 00:00:00")
                        .lt(WorkContactEmployeeEntity::getCreateTime,DateUtil.yesterday().toDateStr() + " 23:59:59"));
        //昨日流失数
        Integer yesterdayLossCount = this.count(
                Wrappers.<ContactLossEntity>lambdaQuery()
                        .eq(ContactLossEntity::getCorpId, corpId)
                        .in(ContactLossEntity::getEmployeeId, employeeIds)
                        .ge(ContactLossEntity::getLossTime, DateUtil.yesterday().toDateStr() + " 00:00:00")
                        .lt(ContactLossEntity::getLossTime, DateUtil.yesterday().toDateStr() + " 23:59:59"));

        ContactLossPageVo vo = new ContactLossPageVo();
        vo.setContactTotalCount(contactTotalCount);
        vo.setContactLossTotalCount(contactLossTotalCount);
        vo.setWxLossCount(wxLossCount);
        vo.setQywxLossCount(qywxLossCount);
        vo.setYesterdayNetGrowthCount(yesterdayAddedCount - yesterdayLossCount < 0 ? 0 :yesterdayAddedCount - yesterdayLossCount);
        vo.setYesterdayLossCount(yesterdayLossCount);
        vo.setYesterdayAddedCount(yesterdayAddedCount);
        return vo;
    }

    @Override
    public ContactLossPageVo getLossStatisticsDatas(String mobile) {
        WorkEmployeeEntity entity = employeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getWxUserId, WorkEmployeeEntity::getName)
                        .eq(WorkEmployeeEntity::getMobile, mobile)
        );

        Set<Integer> employeeIds = new HashSet<>();
        employeeIds.add(entity.getId());
        ContactLossPageVo vo = getLossStatisticsData(employeeIds);
        vo.setCode(entity.getWxUserId());
        vo.setName(entity.getName());
        vo.setEmployeeId(entity.getId());
        return vo;
    }

    @Override
    public List<ContactLossStaticsTendencyVO> getContactLossTotalCount(ContactLossDetailsTendencyDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<ContactLossStaticsTendencyVO> vos = new ArrayList<>();

        hashList.forEach(s -> {
            Integer lossContactCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                lossContactCount = this.count(
                        Wrappers.<ContactLossEntity>lambdaQuery()
                                .eq(ContactLossEntity::getCorpId, corpId)
                                .eq(ContactLossEntity::getTenantId, tenantId)
                                .in(ContactLossEntity::getEmployeeId, employeeIds)
                                .lt(ContactLossEntity::getCreateTime,s.toDateStr() + " 23:59:59"));
            }
            ContactLossStaticsTendencyVO vo = new ContactLossStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(lossContactCount);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public List<ContactLossStaticsTendencyVO> getWxLossCount(ContactLossDetailsTendencyDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<ContactLossStaticsTendencyVO> vos = new ArrayList<>();

        hashList.forEach(s -> {
            Integer wxLossCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                List<ContactLossBO> lossList = baseMapper.getLossList(corpId, tenantId, employeeIds, s.toDateStr()+" 23:59:59");
                wxLossCount = (int)lossList.stream().filter(l->l.getType().equals(1)).count();
            }
            ContactLossStaticsTendencyVO vo = new ContactLossStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(wxLossCount);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public List<ContactLossStaticsTendencyVO> getQywxLossCount(ContactLossDetailsTendencyDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<ContactLossStaticsTendencyVO> vos = new ArrayList<>();

        hashList.forEach(s -> {
            Integer qywxLossCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                List<ContactLossBO> lossList = baseMapper.getLossList(corpId, tenantId, employeeIds, s.toDateStr()+" 23:59:59");
                qywxLossCount = (int)lossList.stream().filter(l->l.getType().equals(2)).count();
            }
            ContactLossStaticsTendencyVO vo = new ContactLossStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(qywxLossCount);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public ContactNoCommunicationPageVo getNoCommunicationStatisticsDatas(Integer deptId, Integer wxDeptId,RemindCommunicationEntity communicationEntity) {
        ContactNoCommunicationPageVo vo;
        Set<Integer> employeeIds = getEmployees(deptId);
        if (employeeIds == null || employeeIds.size() == 0) {
            vo = new ContactNoCommunicationPageVo();
            vo.setContactTotalCount(0);
            vo.setContactNoCommunicationTotalCount(0);
            vo.setYesterdayAddedNoCommunicationCount(0);
            vo.setWxNoCommunicationCount(0);
            vo.setQywxNoCommunicationCount(0);
        } else {
            vo = getNoCommunicationStatisticsData(employeeIds,communicationEntity);
        }
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        vo.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        vo.setName(workDeptEntity.getName());
        return vo;
    }

    @Override
    public ContactNoCommunicationPageVo getNoCommunicationStatisticsData(Set<Integer> employeeIds,RemindCommunicationEntity communicationEntity) {
        Integer corpId = CorpContextHolder.getCorpId();
        ContactNoCommunicationPageVo vo = new ContactNoCommunicationPageVo();
        vo.setContactTotalCount(0);
        vo.setContactNoCommunicationTotalCount(0);
        vo.setYesterdayAddedNoCommunicationCount(0);
        vo.setWxNoCommunicationCount(0);
        vo.setQywxNoCommunicationCount(0);
        //客户总数
        Integer contactTotalCount = workContactService.countByEmployeeIds(employeeIds, corpId, new DateTime().toDateStr() + " 23:59:59");

        //未交流客户总数
        Integer contactNoCommunicationTotalCount = 0;

        //至前天未交流客户数
        Integer noCommunicationContactFromYesterdayTotalCount = 0;
        //至昨天未交流客户数
        Integer noCommunicationContactFromDayBeforeYesterdayTotalCount = 0;

        //未交流微信客户数
        Integer wxNoCommunicationCount = 0;

        //未交流企业微信用户数
        Integer qywxNoCommunicationCount = 0;

        List<Integer> tagIds = JSONUtil.toList(JSONUtil.parseArray(communicationEntity.getTagIds()),Integer.class);
        if (tagIds.isEmpty()) {
            return vo;
        }
        List<String> employeeNames = workEmployeeService.listByIds(employeeIds)
                .stream()
                .map(WorkEmployeeEntity::getName)
                .collect(Collectors.toList());
        List<ContactByTagDto> contactByTagDtoList = contactMapper.getContactByEmployees(corpId, tagIds, employeeNames);
        for (ContactByTagDto contact : contactByTagDtoList) {
            //最近一次聊天记录
            WorkMsgEntity workMsgEntity = workMsgMapper.countTime(contact.getWxUserId(),contact.getWxExternalUserid(),corpId);
            if (workMsgEntity == null) {
                continue;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date yesterdayTime =DateUtil.yesterday().toSqlDate();
            Date nowTime =DateUtils.asDate(LocalDateTime.now());
            Date endTime = DateUtil.parseDateTime(sdf.format(new Date(Long.parseLong(workMsgEntity.getMsgTime())))).toSqlDate();
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE,-2);
            Date dayBeforeYesterdayTime = cal.getTime();

            //至今未交流天数
            long noCommunicationDaysFromToday = DateUtil.between(endTime, nowTime, DateUnit.DAY);
            //至昨天未交流天数
            long noCommunicationDaysFromYesterday = DateUtil.between(endTime, yesterdayTime, DateUnit.DAY);
            //至前天未交流天数
            long noCommunicationDaysFromDayBeforeYesterday = DateUtil.between(endTime, dayBeforeYesterdayTime, DateUnit.DAY);
            if (noCommunicationDaysFromToday > communicationEntity.getTime()) {
                contactNoCommunicationTotalCount += 1;
                if (contact.getContactType().equals(1)) {
                    wxNoCommunicationCount += 1;
                } else if (contact.getContactType().equals(2)) {
                    qywxNoCommunicationCount += 1;
                }
            }
            if (noCommunicationDaysFromYesterday > communicationEntity.getTime()) {
                noCommunicationContactFromYesterdayTotalCount += 1;
            }
            if (noCommunicationDaysFromDayBeforeYesterday > communicationEntity.getTime()) {
                noCommunicationContactFromDayBeforeYesterdayTotalCount += 1;
            }
        }

        vo.setContactTotalCount(contactTotalCount);
        vo.setContactNoCommunicationTotalCount(contactNoCommunicationTotalCount);
        vo.setYesterdayAddedNoCommunicationCount(noCommunicationContactFromDayBeforeYesterdayTotalCount - noCommunicationContactFromYesterdayTotalCount < 0 ? 0 : noCommunicationContactFromDayBeforeYesterdayTotalCount - noCommunicationContactFromYesterdayTotalCount);
        vo.setWxNoCommunicationCount(wxNoCommunicationCount);
        vo.setQywxNoCommunicationCount(qywxNoCommunicationCount);
        return vo;
    }

    @Override
    public ContactNoCommunicationPageVo getNoCommunicationStatisticsDatas(String mobile,RemindCommunicationEntity communicationEntity) {
        WorkEmployeeEntity entity = employeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getWxUserId, WorkEmployeeEntity::getName)
                        .eq(WorkEmployeeEntity::getMobile, mobile)
        );

        Set<Integer> employeeIds = new HashSet<>();
        employeeIds.add(entity.getId());
        ContactNoCommunicationPageVo vo = getNoCommunicationStatisticsData(employeeIds,communicationEntity);
        vo.setCode(entity.getWxUserId());
        vo.setName(entity.getName());
        vo.setEmployeeId(entity.getId());
        return vo;
    }

    @Override
    public List<ContactNoCommunicationStaticsTendencyVO> getContactNoCommunicationTotalCount(ContactNoCommunicationTendencyDTO dto,RemindCommunicationEntity communicationEntity) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        List<ContactNoCommunicationStaticsTendencyVO> vos = new ArrayList<>();
        List<Integer> tagIds = JSONUtil.toList(JSONUtil.parseArray(communicationEntity.getTagIds()),Integer.class);
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        if (tagIds.isEmpty()) {
            hashList.forEach(s ->{
                ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(0);
                vos.add(vo);
            });
            return vos;
        }
        List<String> employeeNames = employeeIds.isEmpty() ? new ArrayList<String>() : workEmployeeService.listByIds(employeeIds)
                .stream()
                .map(WorkEmployeeEntity::getName)
                .collect(Collectors.toList());
        //当前机构所有成员下符合条件的客户
        List<ContactByTagDto> contactByTagDtoList = employeeNames.isEmpty() ? new ArrayList<ContactByTagDto>() : contactMapper.getContactByEmployees(corpId, tagIds, employeeNames);
        hashList.forEach(s -> {
            Integer contactNoCommunicationTotalCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                for (ContactByTagDto contact : contactByTagDtoList) {
                    //最近一次聊天记录
                    WorkMsgEntity workMsgEntity = workMsgMapper.countTime(contact.getWxUserId(),contact.getWxExternalUserid(),corpId);
                    if (workMsgEntity == null) {
                        continue;
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date targetTime = s.toSqlDate();
                    Date endTime = DateUtil.parseDateTime(sdf.format(new Date(Long.parseLong(workMsgEntity.getMsgTime())))).toSqlDate();

                    //未交流天数
                    long noCommunicationDays = DateUtil.between(endTime, targetTime, DateUnit.DAY);
                    if (noCommunicationDays > communicationEntity.getTime()) {
                        contactNoCommunicationTotalCount += 1;
                    }
                }
            }
            ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(contactNoCommunicationTotalCount);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public List<ContactNoCommunicationStaticsTendencyVO> getWxNoCommunicationCount(ContactNoCommunicationTendencyDTO dto,RemindCommunicationEntity communicationEntity) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        List<ContactNoCommunicationStaticsTendencyVO> vos = new ArrayList<>();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<Integer> tagIds = JSONUtil.toList(JSONUtil.parseArray(communicationEntity.getTagIds()),Integer.class);
        if (tagIds.isEmpty()) {
            hashList.forEach(s ->{
                ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(0);
                vos.add(vo);
            });
            return vos;
        }
        List<String> employeeNames = workEmployeeService.listByIds(employeeIds)
                .stream()
                .map(WorkEmployeeEntity::getName)
                .collect(Collectors.toList());
        //当前机构所有成员下符合条件的客户
        List<ContactByTagDto> contactByTagDtoList = contactMapper.getContactByEmployees(corpId, tagIds, employeeNames);
        hashList.forEach(s -> {
            Integer wxNoCommunicationCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                for (ContactByTagDto contact : contactByTagDtoList) {
                    //最近一次聊天记录
                    WorkMsgEntity workMsgEntity = workMsgMapper.countTime(contact.getWxUserId(),contact.getWxExternalUserid(),corpId);
                    if (workMsgEntity == null) {
                        continue;
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date targetTime = s.toSqlDate();
                    Date endTime = DateUtil.parseDateTime(sdf.format(new Date(Long.parseLong(workMsgEntity.getMsgTime())))).toSqlDate();

                    //未交流天数
                    long noCommunicationDays = DateUtil.between(endTime, targetTime, DateUnit.DAY);
                    if (noCommunicationDays > communicationEntity.getTime() && contact.getContactType().equals(1)) {
                        wxNoCommunicationCount += 1;
                    }
                }
            }
            ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(wxNoCommunicationCount);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public List<ContactNoCommunicationStaticsTendencyVO> getQywxNoCommunicationCount(ContactNoCommunicationTendencyDTO dto,RemindCommunicationEntity communicationEntity) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        Integer corpId = CorpContextHolder.getCorpId();
        List<ContactNoCommunicationStaticsTendencyVO> vos = new ArrayList<>();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<Integer> tagIds = JSONUtil.toList(JSONUtil.parseArray(communicationEntity.getTagIds()),Integer.class);
        if (tagIds.isEmpty()) {
            hashList.forEach(s ->{
                ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(0);
                vos.add(vo);
            });
            return vos;
        }
        List<String> employeeNames = workEmployeeService.listByIds(employeeIds)
                .stream()
                .map(WorkEmployeeEntity::getName)
                .collect(Collectors.toList());
        //当前机构所有成员下符合条件的客户
        List<ContactByTagDto> contactByTagDtoList = contactMapper.getContactByEmployees(corpId, tagIds, employeeNames);
        hashList.forEach(s -> {
            Integer qywxNoCommunicationCount = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                for (ContactByTagDto contact : contactByTagDtoList) {
                    //最近一次聊天记录
                    WorkMsgEntity workMsgEntity = workMsgMapper.countTime(contact.getWxUserId(),contact.getWxExternalUserid(),corpId);
                    if (workMsgEntity == null) {
                        continue;
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date targetTime = s.toSqlDate();
                    Date endTime = DateUtil.parseDateTime(sdf.format(new Date(Long.parseLong(workMsgEntity.getMsgTime())))).toSqlDate();

                    //未交流天数
                    long noCommunicationDays = DateUtil.between(endTime, targetTime, DateUnit.DAY);
                    if (noCommunicationDays > communicationEntity.getTime() && contact.getContactType().equals(2)) {
                        qywxNoCommunicationCount += 1;
                    }
                }
            }
            ContactNoCommunicationStaticsTendencyVO vo = new ContactNoCommunicationStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(qywxNoCommunicationCount);
            vos.add(vo);
        });
        return vos;
    }

    private void translation(WorkContactEntity contactEntity, WorkEmployeeEntity employeeEntity, MsgVo vo, WorkMsgEntity f) {
        String wxId = JSONArray.parseArray(f.getTolist()).get(0).toString();
        if (wxId == contactEntity.getWxExternalUserid()) {
            vo.setTo(contactEntity.getName());
            vo.setFrom(employeeEntity.getName());
        }
        if (wxId == employeeEntity.getWxUserId()) {
            vo.setTo(employeeEntity.getName());
            vo.setFrom(contactEntity.getName());
        }

    }


    private Set<Integer> getEmployees(Integer deptId) {
        R r = remoteDeptService.getDeptsAndUsers(deptId);
        log.info("r:{}",r);
        Map<String, Object> data = (Map) r.getData();
        List<Integer> wxDeptIds = (List<Integer>) data.get("wxDeptIds");
        List<String> userMobiles = (List<String>) data.get("userMobiles");
        return employeeService.getEmployeeIds(wxDeptIds, userMobiles);
    }

}
